package model

import (
	"context"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"reflect"
)

var SortType = g.SliceStr{"desc", "asc"}

var FilterType = g.SliceStr{"=", ">", "<", ">=", "<=", "between", "like"}

type (
	QueryModel struct {
		Method    string
		Table     string   `v:"required#请选择表名"`
		Column    []string `d:"*"`
		Condition []Filter `v:"array#请求condition参数格式有误"`
		OrderBy   []Order  `v:"array#请求orderby参数格式有误"`
		GroupBy   []Group  `v:"array#请求groupby参数格式有误"`
		PageInfo
	}

	Filter struct {
		Field  string
		Type   string
		Value  interface{}
		Format string
	}

	Order struct {
		Field string
		Sort  string
	}

	Group struct {
		Field  string
		Having string
	}
)

func (m *QueryModel) Model(db, table string) *gdb.Model {
	return g.DB(db).Model(table)
}

func (m *QueryModel) Format(value interface{}, format string) interface{} {
	if format == "int" {
		return gconv.Int(value)
	} else if format == "string" {
		return gconv.String(value)
	}
	return nil
}

func RuleArray(ctx context.Context, rule string, value interface{}, message string, data interface{}) error {
	if value == nil {
		return nil
	}
	rv := reflect.ValueOf(value)
	kind := rv.Kind()
	if kind == reflect.Ptr {
		rv = rv.Elem()
		kind = rv.Kind()
	}
	switch kind {
	case reflect.Array, reflect.Slice:
		return nil
	default:
		return gerror.New(message)
	}
}
